<?php

namespace app\admin\controller\auth;

use app\admin\model\AdminRule;
use ba\Random;
use Throwable;
use think\facade\Db;
use app\common\controller\Backend;
use app\admin\model\Admin as AdminModel;

class Admin extends Backend
{
    /**
     * 模型
     * @var object
     * @phpstan-var AdminModel
     */
    protected object $model;

    protected array|string $preExcludeFields = ['create_time', 'update_time', 'password', 'salt', 'login_failure', 'last_login_time', 'last_login_ip'];

    protected array|string $quickSearchField = ['username', 'nickname'];

    /**
     * 开启数据限制
     */
    protected string|int|bool $dataLimit = false;

    protected string $dataLimitField = 'id';

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new AdminModel();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $custom_where = [];
        $custom_where['outstation_id'] = $this->outstation_id;
        $custom_where['hide'] = 0;


        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withoutField('login_failure,password,salt')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where($custom_where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 添加
     * @throws Throwable
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            if(empty($data['username'])) $this->error('账号不能为空');
            if(empty($data['password'])) $this->error('密码不能为空');
            $where = [
                'outstation_id' => $this->outstation_id,
                'username' => $data['username']
            ];
            if(Db::name('admin')->where($where)->find()) $this->error('账号已存在');

            $salt   = Random::build('alnum', 16);
            $passwd = encrypt_password($data['password'], $salt);

            $data['salt']     = $salt;
            $data['password'] = $passwd;

            $rules = $data['rules'];
            unset($data['rules']);
            $data['pid'] = $this->auth->id;
            $data['outstation_id'] = $this->outstation_id;
            $data['create_time'] = $this->timestamp;

            $admin_id = Db::name('admin')->insertGetId($data);
            $admin_access_insert = [
                'rules' => implode(',', $rules),
                'admin_id' => $admin_id
            ];
            db::name('admin_access')->insert($admin_access_insert);
            $this->success();
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 编辑
     * @throws Throwable
     */
    public function edit($id = null): void
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            if ($this->auth->id == $data['id'] && $data['status'] == '0') {
                $this->error(__('Please use another administrator account to disable the current account!'));
            }
            $where = [
                ['id', '<>', $row['id']],
                ['username', '=', $data['username']],
                ['outstation_id', '=', $this->outstation_id]
            ];
            $res = db::name('admin')->where($where)->find();
            if($res) $this->error('账号已存在');

            if (isset($data['password']) && $data['password']) {
                $this->model->resetPassword($data['id'], $data['password']);
            }

            $data   = $this->excludeFields($data);
//            print_r($data);die;
            $result = false;
            $this->model->startTrans();
            try {

                if($row['id'] != $this->auth->id){
                    $admin_access_update = [
                        'rules' => implode(',', $data['rules'])
                    ];
                    db::name('admin_access')->where(['admin_id' => $row['id']])->update($admin_access_update);
                }


                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        unset($row['salt'], $row['login_failure']);
        $row['password'] = '';

        $row['rules'] = Db::name('admin_access')->where(['admin_id' => $row['id']])->value('rules');
        $row['rules'] = empty($row['rules']) ? [] : explode(',', $row['rules']);


        // 读取所有pid，全部从节点数组移除，父级选择状态由子级决定
        $pidArr = AdminRule::field('pid')
            ->distinct(true)
            ->where('id', 'in', $row->rules)
            ->select()->toArray();
        $rules  = $row['rules'];
        foreach ($pidArr as $item) {
            $ruKey = array_search($item['pid'], $rules);
            if ($ruKey !== false) {
                unset($rules[$ruKey]);
            }
        }
        $row['rules'] = array_values($rules);

        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 删除
     * @param null $ids
     * @throws Throwable
     */
    public function del($ids = null): void
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $pk    = $this->model->getPk();
        $data  = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        $this->model->startTrans();
        try {
            foreach ($data as $v) {
                if ($v->id != $this->auth->id) {
                    $count += $v->delete();
                    Db::name('admin_group_access')
                        ->where('uid', $v['id'])
                        ->delete();
                }
            }
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    /**
     * 检查分组权限
     * @throws Throwable
     */
    public function checkGroupAuth(array $groups): void
    {
        if ($this->auth->isSuperAdmin()) {
            return;
        }
        $authGroups = $this->auth->getAllAuthGroups('allAuthAndOthers');
        foreach ($groups as $group) {
            if (!in_array($group, $authGroups)) {
                $this->error(__('You have no permission to add an administrator to this group!'));
            }
        }
    }
}